<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 19-4-17
 * Time: 下午4:03
 */

namespace common\components\wtools\tools;


use Ramsey\Uuid\Uuid;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\db\Expression;

class Model extends \yii\base\Model
{
    /**
     * 获取 Model 错误信息中的 第一条，无错误时 返回 null
     * @param \yii\base\Model $model
     * @return mixed|string
     */
    public static function getModelError($model) {
        $errors = $model->getErrors();    //得到所有的错误信息
        if(!is_array($errors)) return '';
        $firstError = array_shift($errors);
        if(!is_array($firstError)) return '';
        return array_shift($firstError);
    }

    /**
     * 给模型键赋唯一值
     * @param ActiveRecord $model
     * @param string $k
     * @param int $len
     */
    public static function setUniqueStrForModelKey(&$model, $k, $len = 32)
    {
        if ($len < 32) throw new \Exception('长度不能小于32');
//        $model->$k = \Yii::$app->security->generateRandomString($len);
        $model->$k = md5(Uuid::uuid4()->toString());
        if ($len > 32) {
            $randomStr = \Yii::$app->security->generateRandomString($len - 32);
            $model->$k .= $randomStr;
        }
        if ($model::findOne([$k => $model->$k])){
            self::setUniqueStrForModelKey($model, $k, $len);
        }
    }

    /**
     * 强制同步多对多关联
     * @param ActiveRecord $model
     * @param string $relationModelClass
     * @param string $relationName
     * @param array $data
     * @return void
     */
    public static function syncManyHasManyForce(&$model, $relationModelClass, $relationName, $data, $relationKey = 'pid', $modelPrimaryKey = 'id', $relationPrimaryKey = 'id')
    {
        $model::getDb()->transaction(function () use ($model, $relationModelClass, $relationName, $data, $relationKey, $modelPrimaryKey, $relationPrimaryKey) {
            $hasIds = [];
            foreach ($model->$relationName as $k => $v) {
                $hasIds[] = $v->$relationPrimaryKey;
            }
            $deleteIds = array_diff($hasIds, array_column($data, $relationPrimaryKey));
            (new $relationModelClass)::deleteAll([$relationPrimaryKey => $deleteIds]);
            foreach ($data as $k => $v) {
                if (!in_array($v[$relationPrimaryKey], $hasIds)) {
                    $toSaveData = [];
                    foreach ($v as $k1 => $v1) {
                        if ($k1 == $relationPrimaryKey) continue;
                        $toSaveData[Tools::uncamelize($k1)] = $v1;
                    }
                    $toSaveData[$relationKey] = $model->$modelPrimaryKey;
                    $m = new $relationModelClass;
                    $m->load($toSaveData, '');
                    if (!$m->save()) {
                        throw new \Exception('同步失败：'.self::getModelError($m));
                    }
                }
            }
        });
    }

    /**
     * 设置uuid
     * @param $modelArr
     * @return array
     * @throws \yii\base\Exception
     */
    public static function setUuidForModels($modelArrs)
    {
        foreach ($modelArrs as $k => $v) {
            if (!isset($v['uuid'])) {
                $modelArrs[$k]['uuid'] = Tools::generateHasDateUniqueString();
            }
        }
        return $modelArrs;
    }
}
